package webEquipeRechercheGwt.client.allEntityShowingPanel;

import java.util.ArrayList;
import java.util.Collection;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllSoftware;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllSoftwaresImplAllSoftwarePanel;
import webEquipeRechercheGwt.client.entityMirror.SoftwareMirror;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerGetSoftwareCreationLabel;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerSoftware;
import webEquipeRechercheGwt.client.services.SoftwareService;
import webEquipeRechercheGwt.client.services.SoftwareServiceAsync;
import webEquipeRechercheGwt.client.structure.DataShowingPanel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;

public class AllSoftwarePanel extends AllEntityShowingPanel {

	private DataShowingPanel mainPanel;
	private Collection<SoftwareMirror> softwares;
	
	public AllSoftwarePanel(DataShowingPanel mainPanel) {
		super();
		this.mainPanel = mainPanel;
		softwares = new ArrayList<SoftwareMirror>();
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		updateLabels();
		loadSoftwaresFromServer();
	}
	
	private void loadSoftwaresFromServer(){
		SoftwareServiceAsync service = GWT.create(SoftwareService.class);
		AsyncCallback<Collection<SoftwareMirror>> callback = new CallBackGetAllSoftware(new CommandGetAllSoftwaresImplAllSoftwarePanel(this));
		service.getSoftwares(callback);
	}

	public void setSoftwares(Collection<SoftwareMirror> persons) {
		this.softwares = persons;
		updateLabels();
	}
	
	private void addCreationLink(){
		Button b = new Button("create new Software");
		ClickHandler handler = new ClickHandlerGetSoftwareCreationLabel(mainPanel);
		b.addClickHandler(handler);
		add(b);
	}
	
	private void updateLabels(){
		clear();
		Label title = new Label("List of all Software");
		add(title);
		for(SoftwareMirror s : softwares){
			Label l = new Label(s.getTitle());
			ClickHandler clickHandler = new ClickHandlerSoftware(s, mainPanel);
			l.addClickHandler(clickHandler);
			add(l);
		}
		addCreationLink();
	}

}
